package com.shop.service.user.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shop.service.module.entity.AddressEntity;
import com.shop.service.module.entity.Result;
import com.shop.service.module.service.AddressService;
import com.shop.service.user.configuration.PageConfig;
import org.apache.http.HttpRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author Wenjl
 */
@RestController
@RequestMapping("address")
public class AddressController {
    @Autowired
    private AddressService addressService;

    @GetMapping("list/page")
    public Result getListPage(@RequestParam(value = "pno", defaultValue = "1") Integer pno,
                              @RequestParam(value = "psize", defaultValue = "10") Integer psize,
                              HttpServletRequest request) {
        Long id = getUserId(request);

        Page<AddressEntity> page = new Page<>(pno, psize);
        QueryWrapper<AddressEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", id);
        Page<AddressEntity> result = addressService.page(page, queryWrapper);
        JSONObject data = new JSONObject();
        JSONObject jsonResult = new JSONObject();
        jsonResult.put("pno", pno);
        jsonResult.put("psize", psize);
        jsonResult.put("pCount", result.getPages());
        jsonResult.put("totalElements", result.getTotal());
        data.put("list", result.getRecords());
        data.put("page", jsonResult);
        return Result.end(200, data, "查询成功");


    }

    @PutMapping("insert")
    public Result insert(@RequestBody AddressEntity addressEntity, HttpServletRequest request) {
        Long id = getUserId(request);
        addressEntity.setUserId(id.longValue());

        boolean result = addressService.save(addressEntity);
        if (result) {
            //判断收货地址是不是默认收货地址
            if (addressEntity.getIsDefault() == 1) {
                QueryWrapper<AddressEntity> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("is_default", 1);
                queryWrapper.eq("user_id", id);
                queryWrapper.ne("id", addressEntity.getId());
                //获取原来的默地址
                List<AddressEntity> list = addressService.list(queryWrapper);

                //如果说集合的长度大于0就说明原来有默认收货地址，则需要将原来的默认地址取消
                if (list.size() > 0) {
                    AddressEntity addressEntity1 = list.get(0);
                    addressEntity1.setIsDefault(0);
                    addressService.updateById(addressEntity1);
                }
            }
        }
        return result ? Result.end(200, "", "添加成功") : Result.end(500, "", "添加失败");
    }

    @GetMapping("find/id/{id}")
    public Result getAddressById(@PathVariable Long id) {
        AddressEntity addressEntity = addressService.getById(id);
        return Result.end(200, addressEntity, "查询成功");
    }

    @PutMapping("update")
    public Result update(@RequestBody AddressEntity addressEntity) {

        boolean result = addressService.updateById(addressEntity);
        if (result) {
                                                                                              //判断收货地址是不是默认收货地址
            if (addressEntity.getIsDefault() == 1) {
                System.out.println("addressEntity.getIsDefault() == 1");
                QueryWrapper<AddressEntity> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("is_default", 1);
                queryWrapper.eq("user_id", addressEntity.getUserId());
                queryWrapper.ne("id", addressEntity.getId());
                //获取原来的默地址
                List<AddressEntity> list = addressService.list(queryWrapper);

                //如果说集合的长度大于0就说明原来有默认收货地址，则需要将原来的默认地址取消
                if (list.size() > 0) {
                    AddressEntity addressEntity1 = list.get(0);
                    addressEntity1.setIsDefault(0);
                    addressService.updateById(addressEntity1);
                }
            }
        }
        return result ? Result.end(200, "", "修改成功") : Result.end(500, "", "修改失败");
    }

    @DeleteMapping("delete/id/{id}")
    private Result delete(@PathVariable Long id) {
        boolean result = addressService.removeById(id);
        return result ? Result.end(200, "", "删除成功") : Result.end(500, "", "删除失败");

    }


    private Long getUserId(HttpServletRequest request) {
        String authorization = request.getHeader("Authorization");
        //从加密字符串中去掉Bearer字样
        authorization = authorization.replace("Bearer ", "");
        //通过jwt解密工具将密文解密成原始对象
        Jwt jwtInfo = JwtHelper.decode(authorization);
        //将jwt原始对象转换成字符串
        String jwtStr = jwtInfo.getClaims();
        System.err.println(jwtStr);
        //将jwt的字符串转换成json对象
        JSONObject jwtJSON = JSONObject.parseObject(jwtStr);
        //从jwt字符串中获取userInfo对象
        JSONObject userInfo = JSONObject.parseObject(jwtJSON.get("userInfo").toString());
        Integer id = (Integer) userInfo.get("id");
        return id.longValue();
    }


}
